package core.service;

import core.dao.PostDAO;
import core.entity.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Christian Waickem on 9/29/2014.
 */
@Service
@Transactional(readOnly = true)
public class PostService {

    @Autowired
    PostDAO postDAO;

    public List<Post> getAllPosts() {
        return postDAO.getAllPosts();
    }

    public Post findPostById(long id) {
        return postDAO.findPostById(id);
    }

    public List<Post> getAllShortContent() {

        List<Post> postsList = postDAO.getAllShortContent();
        return stopByLastSpace(postsList);
    }

    public List<Post> searchPostByString(String searchString) {
        List<Post> postsList = postDAO.searchPostsByString(searchString);
        return stopByLastSpace(postsList);
    }

    public List<Post> searchPostByContent(String searchString){
        List<Post> postsList = postDAO.searchPostsByContent(searchString);
        return stopByLastSpace(postsList);
    }

    private static List<Post> stopByLastSpace(List<Post> postsList){
        for (Post post : postsList) {
            String content = post.getContent();
            post.setContent(content.substring(0, content.lastIndexOf(" ") + 1));
        }
        return postsList;
    }
}
